import React, { useEffect, useState } from 'react';
import { XoProTable } from '@/components/XoProTable';
import { Tabs, Button, Card, Statistic, message } from 'antd';
import styles from './index.less';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import TabPane from '@ant-design/pro-card/lib/components/TabPane';
import type { Situation } from '@/models/situation';
import { history, Link } from 'umi';
import {
  courseItemExport,
  courseItemList,
  gameLessonList,
  groupOptionList,
  playGameList,
  userGameStatList,
} from '@/services/situation';
import moment from 'moment';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import { ProFormSelect, DrawerForm } from '@ant-design/pro-form';
import { onRequestNickName } from '@/utils/requestPhone';
// import { blobToJson } from '@/utils/export';
import StudentInfo from '../StudentInfo';
import { getInfoByStepType } from '@/services/student';
import { useRef } from 'react';
const lessonList = [
  '第一关：认识棋盘',
  '第二关：棋子的气',
  '第三关：打吃和逃跑',
  '第四关：虎口',
  '小剧场：下棋礼仪',
  '第六关：禁入点',
  '第七关：打劫的概念',
  '第八关：打二还一',
  '第九关：连接及连接棋型',
  '第十关：断与断打',
  '小剧场：术语（双、尖、跳）',
  '第十二关：互相打吃',
  '第十三关：双打吃',
  '第十四关：关门吃，抱吃',
  '第十五关：一线吃子',
  '小剧场：专心致志',
  '第十七关：二线吃子',
  '第十八关：枷吃',
  '第十九关：征吃',
  '第二十关：无法吃掉的征吃',
  '小剧场：下棋不耍赖',
  '第二十二关：连续打吃',
  '第二十三关：接不归',
  '第二十四关：倒扑',
  '第二十五关：逃跑技巧',
  '小剧场：围棋起源',
  '第二十七关：攻防技巧',
  '第二十八关：对杀的概念',
  '第二十九关：暗气与不入气',
  '第三十关：公气与双活',
  '小剧场：当湖第十局',
  '第三十二关：对杀目标判断',
  '第三十三关：收气的方向',
  '第三十四关：延气的技巧',
  '第三十五关：实战对杀思考',
  '小剧场：学无止境',
];
interface Params {
  dataInfo: any;
  courseId: any;
}
export default function StudySituation(props: Params) {
  const [selectData, setData] = useState<any>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [phoneValue, setPhoneValue] = useState<any>();
  const [optionsValue, setOptionValue] = useState<any>();
  const [item1, setItemList] = useState<any[]>([]);
  const [studyDataItem, setStudyDataItem] = useState<any[]>([]);
  // 课程id
  const { id } = history.location.query || {};

  const [shiwForm, setShowForm] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [idx, setIndex] = useState<any>();
  const [idx2, setIndex2] = useState<any>();
  const [ids, setUserId] = useState<any>();
  const [ids2, setUserId2] = useState<any>();
  const [ids4, setUserId3] = useState<any>();
  const [ids3, setId] = useState<any>();
  const { dataInfo, courseId } = props;
  const [typeData, setTypeData] = useState<Situation>();
  // const { dataInfo } = props;
  // const [typeData, setTypeData] = useState<Situation>();
  const showForm = async (record: any, index: number) => {
    setIndex(index);
    setShowForm(true);
  };
  const showGameLesson = async (record: any, index: number) => {
    setIndex2(index);
    setVisible(true);
  };

  useEffect(() => {
    (async () => {
      const res = await groupOptionList({ activityId: id });
      const res1 = res.result?.map((item: any) => {
        return { label: item.name, value: item.id };
      });
      setData(res1);
    })();
    (async () => {
      const data = (await getInfoByStepType({ id: id }))?.result;
      setTypeData(data);
      // console.log(data);
    })();
  }, []);
  const columns: ProColumns<Situation>[] = [
    {
      dataIndex: 'id',
      title: '条目ID',
    },
    {
      dataIndex: 'name',
      title: '条目名称',
      render: (_, record) => {
        return (
          <Link to={`/course/detail?id=${record.id}&activityId=${id}`} target="_blank">
            <a
            // onClick={() => {
            //   history.push({
            //     pathname: '/course/detail',
            //     query: {
            //       id: `${record.id}`,
            //       activityId: id

            //     },
            //   });
            // }}
            >
              {_}
            </a>
          </Link>
        );
      },
    },
    {
      dataIndex: 'startTime',
      title: '条目开始时间',
      render: (_, record) => {
        if (record.unlockType == 1) {
          return (
            <div>
              {record.startTime
                ? moment(record.startTime).format('YYYY-MM-DD hh:mm') + '(购课后解锁)'
                : '-'}
            </div>
          );
        } else {
          return (
            <div>
              {record.startTime ? moment(record.startTime).format('YYYY-MM-DD hh:mm') : '-'}
            </div>
          );
        }
      },
    },
    {
      dataIndex: 'stepCount',
      title: '学习环节数量',
    },
    {
      dataIndex: 'finishedUserCount',
      title: '完成所有环节人数',
    },
    {
      dataIndex: 'totalUserCount',
      title: '总人数',
    },
    {
      dataIndex: 'stepFinishRate',
      title: '环节完成率',
      render: (_, record) => {
        return (
          <div>
            {record.stepFinishRate !== undefined ? `${record.stepFinishRate.toFixed(2)}%` : '-'}
          </div>
        );
      },
    },
  ];
  const gameLessonColumns: ProColumns<Situation>[] = [
    {
      dataIndex: 'uid',
      title: '用户ID',
      search: false,
      // fixed: 'left',
      // width: 80,
    },
    {
      dataIndex: 'nickname',
      title: '用户昵称',
      search: false,
      render: (text: any, record: any, index: number) => {
        return <a onClick={() => showGameLesson(record, index)}>{text}</a>;
        // if (record.nickname) {
        //   return (
        //     <a onClick={() => showForm(record, index)}>{text}</a>
        //   )
        // }else{
        //   return (
        //     <div>-</div>
        //   )
        // }
      },
    },
    {
      dataIndex: 'uid',
      title: '昵称/手机号',
      width: 150,
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormSelect
            fieldProps={{
              onChange: (val) => setPhoneValue(val),
            }}
            wrapperCol={{ span: 24 }}
            showSearch
            debounceTime={500}
            name="uid"
            request={onRequestNickName}
          />
        );
      },
    },
    {
      dataIndex: 'realName',
      title: '真实姓名',
      search: false,
      // width: 200,
    },
    {
      dataIndex: 'phone',
      title: '手机号',
      search: false,
      // width: 200,
    },
    {
      dataIndex: 'groupName',
      title: '班级',
      width: 80,
      renderFormItem: () => {
        return (
          <ProFormSelect
            fieldProps={{
              onChange: (val) => setOptionValue(val),
            }}
            name="groupId"
            placeholder="请选择"
            debounceTime={500}
            colon={false}
            options={selectData}
          />
        );
      },
    },
    {
      dataIndex: 'teacherName',
      title: '辅导老师',
      // width: 180,
      search: false,
    },
  ];
  const lessonColumns: any = lessonList.map((value, index) => {
    const item: ProColumns<Situation> = {
      title: value,
      search: false,
      render: (_, record) => {
        const lessonMap = record.lessonMap || {};
        const lessonData = lessonMap[`${index + 1}`] || {};
        return <div>{lessonData.historyStars ?? '-'}</div>;
      },
    };
    return item;
  });
  gameLessonColumns.push(...lessonColumns);
  // 棋灵对弈
  const playGameColumns: ProColumns<Situation>[] = [
    {
      dataIndex: 'uid',
      title: '用户ID',
      width: 100,
      search: false,
    },
    {
      dataIndex: 'nickname',
      title: '用户昵称',
      width: 150,
      search: false,
      render: (text: any, record: any, index: number) => {
        return <a onClick={() => showForm(record, index)}>{text}</a>;
        // if (record.nickname) {
        //   return (
        //     <a onClick={() => showForm(record, index)}>{text}</a>
        //   )
        // }else{
        //   return (
        //     <div>-</div>
        //   )
        // }
      },
    },
    {
      dataIndex: 'uid',
      title: '昵称/手机号',
      width: 150,
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormSelect
            wrapperCol={{ span: 24 }}
            fieldProps={{
              onChange: (val) => setPhoneValue(val),
            }}
            showSearch
            debounceTime={500}
            placeholder="请选择"
            name="uid"
            request={onRequestNickName}
          />
        );
      },
    },
    {
      dataIndex: 'realName',
      title: '真实姓名',
      width: 150,
      search: false,
    },
    {
      dataIndex: 'phone',
      title: '手机号',
      width: 200,
      search: false,
    },

    {
      dataIndex: 'groupName',
      title: '班级',
      width: 80,
      renderFormItem: () => {
        return (
          <ProFormSelect
            fieldProps={{
              onChange: (val) => setOptionValue(val),
            }}
            name="groupId"
            placeholder="请选择"
            debounceTime={500}
            colon={false}
            options={selectData}
          />
        );
      },
    },
    {
      dataIndex: 'teacherName',
      title: '辅导老师',
      width: 150,
      search: false,
    },
    {
      dataIndex: 'playGradeName',
      title: '棋士品级',
      width: 150,
      search: false,
    },
    {
      dataIndex: 'playScore',
      title: '当前分数',
      width: 150,
      search: false,
    },
    {
      dataIndex: 'situation',
      title: '开课后分数情况',
      width: 300,
      search: false,
      render: (_, record) => {
        return (
          <>
            {record.oldPlayGradeName && record.playGradeName ? (
              <div>
                {' '}
                {record.oldPlayGradeName || '-'}→{record.playGradeName || '-'}
              </div>
            ) : (
              '-'
            )}

            {record.addedPlayScore && record.addedPlayScore > 0 ? (
              <Statistic
                value={record.addedPlayScore}
                precision={2}
                valueStyle={{ color: '#cf1322' }}
                prefix={<ArrowUpOutlined />}
              />
            ) : null}
            {record.addedPlayScore && record.addedPlayScore < 0 ? (
              <Statistic
                value={record.addedPlayScore}
                precision={2}
                valueStyle={{ color: '#3f8600' }}
                prefix={<ArrowDownOutlined />}
              />
            ) : null}
          </>
        );
      },
    },
    {
      dataIndex: 'up',
      title: '开课后对弈提升(胜/总)',
      width: 250,
      search: false,
      render: (_, record) => {
        return (
          <div>
            {record.winCount !== null && record.totalCount !== null
              ? ` ${record.winCount} / ${record.totalCount}`
              : '-'}
          </div>
        );
      },
    },
    {
      dataIndex: 'totalUp',
      title: '对局胜利数/对局总数(胜率)',
      width: 300,
      search: false,
      render: (_, record) => {
        return (
          <div>
            {record.allWinCount !== null && record.allCount !== null
              ? `${(((record.allWinCount ?? 0) / (record.allCount ?? 0)) * 100).toFixed(2)}%`
              : '-'}
          </div>
        );
      },
    },
    {
      dataIndex: 'weekUp',
      title: '本周胜利/本周对弈',
      width: 250,
      search: false,
      render: (_, record) => {
        return (
          <div>
            {record.weekTotalCount !== null
              ? `${record.weekWinCount ?? '-'} / ${record.weekTotalCount ?? '-'}`
              : '-'}
          </div>
        );
      },
    },
    {
      dataIndex: 'monthUp',
      title: '本月胜利/本月对弈',
      width: 250,
      search: false,
      render: (_, record) => {
        return (
          <div>
            {record.monthTotalCount !== null
              ? `${record.monthWinCount ?? '-'} /${record.monthTotalCount ?? '-'} `
              : '-'}
          </div>
        );
      },
    },
    {
      dataIndex: 'lastGameTime',
      title: '最近一次下棋时间',
      width: 250,
      search: false,
    },
    {
      dataIndex: 'operation',
      title: '操作',
      width: 150,
      search: false,
      fixed: 'right',
      render: (_, record) => {
        return record.allCount ? (
          <Link to={`/course/chess?id=${record.uid}&courseId=${id}`} target="_blank">
            <a>查看棋谱</a>
          </Link>
        ) : null;
      },
    },
  ];
  // 悟空对弈
  const userGameStatListColumns: ProColumns<Situation>[] = [
    {
      dataIndex: 'uid',
      title: '用户ID',
      search: false,
      width: 80,
    },
    {
      dataIndex: 'nickname',
      title: '用户昵称',
      width: 100,
      search: false,
      render: (text: any, record: any, index: number) => {
        return <a onClick={() => showGameLesson(record, index)}>{text}</a>;

        // if (record.nickname) {
        //   return (
        //     <a onClick={() => showForm(record, index)}>{text}</a>
        //   )
        // }else{
        //   return (
        //     <div>-</div>
        //   )
        // }
      },
    },
    {
      dataIndex: 'uid',
      title: '昵称/手机号',
      width: 100,
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormSelect
            wrapperCol={{ span: 24 }}
            fieldProps={{
              onChange: (val) => setPhoneValue(val),
            }}
            showSearch
            debounceTime={500}
            placeholder="请选择"
            name="uid"
            request={onRequestNickName}
          />
        );
      },
    },
    {
      dataIndex: 'realName',
      title: '真实姓名',
      width: 80,
      search: false,
    },
    {
      dataIndex: 'phone',
      title: '手机号',
      width: 100,
      search: false,
    },
    {
      dataIndex: 'reviewCount',
      title: '复盘次数',
      search: false,
      width: 80,
    },
    {
      dataIndex: 'groupName',
      title: '班级',
      width: 80,
      renderFormItem: () => {
        return (
          <ProFormSelect
            fieldProps={{
              onChange: (val) => setOptionValue(val),
            }}
            name="groupId"
            placeholder="请选择"
            debounceTime={500}
            colon={false}
            options={selectData}
          />
        );
      },
    },
    {
      dataIndex: 'teacherName',
      title: '辅导老师',
      width: 100,
      search: false,
    },
    {
      dataIndex: 'curPower',
      title: '当前战力',
      width: 100,
      search: false,
    },
    {
      dataIndex: 'curScore',
      title: '当前分数',
      width: 100,
      search: false,
    },
    {
      dataIndex: 'addedPower',
      title: '开课后战力提升',
      width: 100,
      search: false,
      render: (_, record) => {
        return (
          <>
            {record.addedPower && record.addedPower > 0 ? (
              <Statistic
                value={record.addedPower}
                // precision={2}
                valueStyle={{ color: '#cf1322' }}
                prefix={<ArrowUpOutlined />}
              />
            ) : null}
            {record.addedPower && record.addedPower < 0 ? (
              <Statistic
                value={record.addedPower}
                // precision={2}
                valueStyle={{ color: '#3f8600' }}
                prefix={<ArrowDownOutlined />}
              />
            ) : null}
          </>
        );
      },
    },
    {
      dataIndex: 'addedScore',
      title: '开课后分数提升',
      width: 100,
      search: false,
      render: (_, record) => {
        return (
          <>
            {record.addedScore && record.addedScore > 0 ? (
              <Statistic
                value={record.addedScore}
                // precision={2}
                valueStyle={{ color: ' #cf1322' }}
                prefix={<ArrowUpOutlined />}
              />
            ) : null}
            {record.addedScore && record.addedScore < 0 ? (
              <Statistic
                value={-record.addedScore}
                // precision={2}
                valueStyle={{ color: '#3f8600' }}
                prefix={<ArrowDownOutlined />}
              />
            ) : null}
          </>
        );
      },
    },
    {
      dataIndex: 'up',
      title: '开课后对弈提升(胜/总)',
      width: 150,
      search: false,
      render: (_, record) => {
        return <div>{record.totalCount ? ` ${record.winCount} / ${record.totalCount}` : '-'}</div>;
      },
    },
    {
      dataIndex: 'totalUp',
      title: '对局胜利数/对局总数(胜率)',
      width: 150,
      search: false,
      render: (_, record) => {
        return (
          <div>
            {record.allCount && record.allWinCount
              ? `${((record.allWinCount / record.allCount) * 100)?.toFixed(2)}%`
              : '-'}
          </div>
        );
      },
    },
    {
      dataIndex: 'weekUp',
      title: '本周胜利/本周对弈',
      width: 100,
      search: false,
      render: (_, record) => {
        return (
          <div>
            {record.weekWinCount && record.weekTotalCount
              ? `${record.weekWinCount} / ${record.weekTotalCount}`
              : '-'}
          </div>
        );
      },
    },
    {
      dataIndex: 'monthUp',
      title: '本月胜利/本月对弈',
      width: 100,
      search: false,
      render: (_, record) => {
        return (
          <div>
            {record.monthWinCount && record.monthTotalCount
              ? `${record.monthWinCount} /${record.monthTotalCount} `
              : '-'}
          </div>
        );
      },
    },
    {
      dataIndex: 'lastGameTime',
      title: '最近一次下棋时间',
      width: 180,
      search: false,
    },
    {
      dataIndex: 'operation',
      title: '操作',
      width: 100,
      search: false,
      fixed: 'right',
      render: (_, record) => {
        return (
          <div>
            {record.totalCount ? (
              <Link to={`/course/userGame/chess?id=${record.uid}&courseId=${id}`} target="_blank">
                <a>查看棋谱</a>
              </Link>
            ) : (
              '-'
            )}
          </div>
        );
      },
    },
  ];
  // 棋灵对弈导出
  const exportList = async () => {
    if (item1?.length == 0) {
      message.destroy();
      message.error('没有可导出的数据');
      return;
    }
    setLoading(true);
    const params = {
      activityId: id,
      groupId: optionsValue,
      uid: phoneValue,
    };
    await courseItemExport({
      map: { ...params },
      exportType: 'exportUserPlayGames',
      fileName: `${dataInfo?.name}.xlsx`,
    });
    setLoading(false);
  };
  // 棋灵探险导出
  const exportListGameLesson = async () => {
    if (item1?.length == 0) {
      message.destroy();
      message.error('没有可导出的数据');
      return;
    }
    setLoading(true);
    const params = {
      activityId: id,
      groupId: optionsValue,
      uid: phoneValue,
    };

    await courseItemExport({
      map: { ...params },
      exportType: 'exportUserGameLessons',
      fileName: `${dataInfo?.name}.xlsx`,
    });
    setLoading(false);
  };
  // 学习环节数据导出
  const exportListStudyData = async () => {
    if (studyDataItem?.length == 0) {
      message.destroy();
      message.error('没有可导出的数据');
      return;
    }
    setLoading(true);
    await courseItemExport({
      exportType: 'exportCourseItems',
      map: {
        courseId: Number(id),
      },
      fileName: `${courseId}_学习环节数据_${moment(new Date()).format('YYYY-MM-DD HH时mm分ss秒')}.xlsx`,
    });
    setLoading(false);
  };
  const onReset = () => {
    setPhoneValue('');
    setOptionValue('');
  };
  // 悟空对弈导出
  const exportGameStatList = async () => {
    if (item1?.length == 0) {
      message.destroy();
      message.error('没有可导出的数据');
      return;
    }
    setLoading(true);
    const params = {
        activityId: id,
        groupId: optionsValue,
        uid: phoneValue,
      };
      await courseItemExport({
        map: { ...params },
        exportType: 'exportGokuGameData',
        fileName: `${dataInfo?.name}.xlsx`,
      });
      setLoading(false);
  };
  const ref = useRef<ActionType>()
  const ref1 = useRef<ActionType>()
  const ref2 = useRef<ActionType>()
  return (
    <Card className={styles.card}>
      <Tabs defaultActiveKey="1" type="card">
        <TabPane tab="条目数据" key="1">
          <XoProTable
            onReset={onReset}
            request={async (params) => {
              const body = (await courseItemList({ ...params, courseId: Number(id) }))?.result;
              setStudyDataItem(body?.records);
              return {
                data: body?.records,
                total: body?.total,
              };
            }}
            options={false}
            search={false}
            rowKey="key"
            scroll={{ x: 1000 }}
            hasIndex={false}
            columns={columns}
            toolBarRender={() => [
              <Button key="export" loading={loading} onClick={exportListStudyData}>
                导出学习环节数据
              </Button>,
            ]}
          />
        </TabPane>
        {typeData?.enableGame == 1 ? (
          <TabPane tab="棋灵对弈" key="3">
            <XoProTable
              onReset={onReset}
              // params={{ visible }}
              className={styles.playlist}
              request={async (params: any) => {
                const body = (await playGameList({ ...params, activityId: id }))?.result;
                const ids1 = body.records?.map((item: any) => {
                  return item.uid;
                });
                const ids5 = body.records?.map((item: any) => {
                  return item.id;
                });
                setUserId(ids1);
                setId(ids5);
                setItemList(body?.records);
                return {
                  data: body?.records,
                  total: body?.total,
                };
              }}
              actionRef={ref}
              options={false}
              rowKey="key"
              scroll={{ x: 2000 }}
              hasIndex={false}
              columns={playGameColumns}
              toolBarRender={() => [
                <Button key="export1" loading={loading} onClick={exportList}>
                  导出
                </Button>,
              ]}
            />
            <DrawerForm
              className={styles.drawer_form}
              visible={shiwForm}
              width="80%"
              drawerProps={{
                footerStyle: { display: 'none' },
                closeIcon: false,
                bodyStyle: { padding: '0' },
                closable: false,
                onClose: () => ref.current?.reload(),
                destroyOnClose: true,
              }}
              onVisibleChange={(val) => setShowForm(val)}
            >
              <StudentInfo ids={ids} idx={idx} ids3={ids3} />
            </DrawerForm>
          </TabPane>
        ) : null}
        {typeData?.enableAdventure == 1 ? (
          <TabPane tab="棋灵探险" key="2">
            <XoProTable
              className={styles.playlist}
              request={async (params: any) => {
                const body = (await gameLessonList({ ...params, activityId: id }))?.result;
                const idsPro = body.records?.map((item: any) => {
                  return item.uid;
                });
                const idsPro1 = body.records?.map((item: any) => {
                  return item.id;
                });
                setItemList(body?.records);
                setUserId2(idsPro);
                setUserId3(idsPro1);
                return {
                  data: body?.records,
                  total: body?.total,
                };
              }}
              actionRef={ref1}
              options={false}
              rowKey="key"
              scroll={{ x: 6000 }}
              hasIndex={false}
              columns={gameLessonColumns}
              toolBarRender={() => [
                <Button key="export2" loading={loading} onClick={exportListGameLesson}>
                  导出
                </Button>,
              ]}
            />
            <DrawerForm
              className={styles.drawer_form}
              visible={visible}
              width="80%"
              drawerProps={{
                footerStyle: { display: 'none' },
                closeIcon: false,
                bodyStyle: { padding: '0' },
                closable: false,
                onClose: () => ref1.current?.reload(),
                destroyOnClose: true,
              }}
              onVisibleChange={setVisible}
            >
              <StudentInfo ids={ids2} idx={idx2} ids3={ids4} />
            </DrawerForm>
          </TabPane>
        ) : null}
        {typeData?.aiGoFlag == 1 ? (
          <TabPane tab="悟空对弈" key="4">
            <XoProTable
              onReset={onReset}
              className={styles.playlist}
              request={async (params: any) => {
                const body = (await userGameStatList({ ...params, activityId: id }))?.result;
                setItemList(body?.records);
                const idsPro = body.records?.map((item: any) => {
                  return item.uid;
                });
                const idsPro1 = body.records?.map((item: any) => {
                  return item.id;
                });

                setUserId2(idsPro);
                setUserId3(idsPro1);
                return {
                  data: body?.records,
                  total: body?.total,
                };
              }}
              actionRef={ref2}
              options={false}
              rowKey="key"
              scroll={{ x: 2300 }}
              hasIndex={false}
              columns={userGameStatListColumns}
              toolBarRender={() => [
                <Button key="export2" loading={loading} onClick={exportGameStatList}>
                  导出
                </Button>,
              ]}
            />
            <DrawerForm
              className={styles.drawer_form}
              visible={visible}
              width="80%"
              drawerProps={{
                footerStyle: { display: 'none' },
                closeIcon: false,
                bodyStyle: { padding: '0' },
                closable: false,
                onClose: () => ref2.current?.reload(),
                destroyOnClose: true,
              }}
              onVisibleChange={(val) => setVisible(val)}
            >
              <StudentInfo ids={ids2} idx={idx2} ids3={ids4} />
            </DrawerForm>
          </TabPane>
        ) : null}
      </Tabs>
    </Card>
  );
}
